package com.prawn.user.intercepter;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: zhy
 * @Date: 2019/7/11
 * @Description: 拦截请求，解析请求头中的token进行解析，将令牌存储在Request
 */
@Component
public class JwtIntercepter implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("--拦截器--");

        String authorization = request.getHeader("Authorization");
        if (authorization != null && !"".equals(authorization)) {
            //如果包含Authorization认证信息，则进行解析
            if (authorization.startsWith("Bearer ")) {
                //得到token
                String token = authorization.substring(7);
                //验证令牌
                try {
                    Claims claims = jwtUtil.parseJWT(token);
                    String roles = (String) claims.get("roles");
                    //如果是admin用户
                    if (roles != null && !"".equals("admin")) {
                        request.setAttribute("claims_admin",token);
                    }
                    //如果是普通用户
                    if (roles != null && !"".equals("user")) {
                        request.setAttribute("claims_user",token);
                    }
                } catch (Exception e) {
                    throw new RuntimeException();
                }
            }
        }

        //无论如何都放行
        return true;
    }
}
